from driver import RTC

class SysRtc():
    def __init__(self):
        self.rtc = RTC()
        self.rtc.open()
        self._last_total_seconds = 0
        t = self.rtc.getTime() 
        self.rtc.setTime(t[0],t[1],t[2],t[3]+8,t[4],t[5])


    def sys_rtc(self):
        t = self.rtc.getTime()    
        return (t[0], t[1], t[2], t[3], t[4], t[5])

    def set_time(self,year=2024,month=1,day=1,hour=00,minute=00,second=00):
        self.rtc.setTime(year,month,day,hour,minute,second)

    def getRtcTime(self):
        mydata = self.sys_rtc()
        # print("mydata:",mydata)
        d="{:04d}-{:02d}-{:02d}".format(mydata[0],mydata[1],mydata[2])
        t="{:02d}:{:02d}:{:02d}".format(mydata[3],mydata[4],mydata[5]) 
        
        datatiemstr = d + ' '+ t
        return datatiemstr

    # 反向格式化时间撮
    # def Mktime(self):
    #     return time.mktime(self.mydata)

    def get_next_collection_time_with_time(self, interval_seconds):
        """
        根据设定的采集间隔和传入的时间字符串，计算下一个采集时间点
        参数:
        interval_seconds: 采集间隔（秒）
        current_time_str: 当前时间字符串，格式为 "YYYY-MM-DD HH:MM:SS"
        返回: next_time: 下一个采集时间点（秒）
             wait_seconds: 需要等待的秒数
        """
        
        # 支持的固定时间点（秒）
        supported_intervals = [1, 2, 4, 5, 10, 15, 20, 30, 60, 300, 600,
                               900, 1200, 1800, 3600, 5400, 7200, 10800]
        
        # 如果不是预定义的时间点，直接返回间隔时间
        if interval_seconds not in supported_intervals:
            return None, None

        data_t = self.sys_rtc()
        hour, minute, second = data_t[3], data_t[4], data_t[5]
        # 计算当前时间的总秒数（一天内）
        current_total_seconds = hour * 3600 + minute * 60 + second
        # 添加调试信息
        print("Debug - Current time: %02d:%02d:%02d (total: %d seconds)" % 
              (hour, minute, second, current_total_seconds))
        
        # 计算下一个采集时间点
        next_total_seconds = ((current_total_seconds // interval_seconds) + 1) * interval_seconds
      
        # 处理跨越午夜的情况
        if next_total_seconds >= 86400:  # 24 * 3600
            # 检查是否应该在00:00:00采集
            if next_total_seconds == 86400:
                # 正好在午夜采集
                wait_seconds = 86400 - current_total_seconds
                next_total_seconds = 0  # 表示第二天的00:00:00
            else:
                # 跨越到第二天的其他时间点
                next_total_seconds = next_total_seconds - 86400
                wait_seconds = (86400 - current_total_seconds) + next_total_seconds   
        else:
            # 计算需要等待的秒数
            wait_seconds = next_total_seconds - current_total_seconds
        if wait_seconds <= 0:
            wait_seconds = interval_seconds
            
        return next_total_seconds, wait_seconds

        